"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { 
  GitBranch, 
  GitMerge, 
  GitCommit,
  User,
  Calendar,
  ArrowRight,
  CheckCircle,
  Clock,
  AlertTriangle
} from "lucide-react"
import { cn } from "@/lib/utils"

interface FlowNode {
  id: string
  type: 'state' | 'transition' | 'milestone'
  title: string
  description?: string
  status: 'pending' | 'active' | 'completed' | 'error'
  timestamp?: string
  operator?: string
  position: { x: number; y: number }
  connections: string[]
  metadata?: {
    fromStatus?: string
    toStatus?: string
    event?: string
    note?: string
  }
}

interface ProjectFlowGraphProps {
  projectId: string
  currentStatus: string
  histories: any[]
}

export default function ProjectFlowGraph({ projectId, currentStatus, histories }: ProjectFlowGraphProps) {
  const [nodes, setNodes] = useState<FlowNode[]>([])
  const [selectedNode, setSelectedNode] = useState<FlowNode | null>(null)
  const [viewMode, setViewMode] = useState<'timeline' | 'graph'>('timeline')

  // 状态流转配置
  const stateFlowConfig = {
    '草稿': { next: ['待立项'], color: 'bg-gray-500', icon: GitCommit },
    '待立项': { next: ['已立项', '草稿'], color: 'bg-yellow-500', icon: Clock },
    '已立项': { next: ['设计中', '休眠'], color: 'bg-blue-500', icon: CheckCircle },
    '设计中': { next: ['开发中', '休眠'], color: 'bg-purple-500', icon: GitCommit },
    '开发中': { next: ['测试中', '休眠'], color: 'bg-indigo-500', icon: GitCommit },
    '测试中': { next: ['已完成', '开发中'], color: 'bg-orange-500', icon: AlertTriangle },
    '已完成': { next: ['订单准备', '已归档'], color: 'bg-green-500', icon: CheckCircle },
    '订单准备': { next: ['生产中'], color: 'bg-teal-500', icon: GitBranch },
    '生产中': { next: ['已完成'], color: 'bg-red-500', icon: GitCommit },
    '已归档': { next: ['草稿'], color: 'bg-gray-600', icon: GitCommit },
    '休眠': { next: ['活动中'], color: 'bg-gray-400', icon: Clock }
  }

  useEffect(() => {
    generateFlowNodes()
  }, [currentStatus, histories])

  const generateFlowNodes = () => {
    const generatedNodes: FlowNode[] = []
    const processedStates = new Set<string>()
    
    // 添加历史记录节点
    histories.forEach((history, index) => {
      if (history.action === 'STATUS_CHANGED' && history.description) {
        const node: FlowNode = {
          id: `history-${history.id}`,
          type: 'transition',
          title: history.description,
          description: history.description,
          status: 'completed',
          timestamp: history.createdAt,
          operator: history.user?.name || '未知用户',
          position: { x: index * 200, y: 100 },
          connections: [],
          metadata: {
            fromStatus: history.fromLevel1,
            toStatus: history.toLevel1,
            note: history.description
          }
        }
        generatedNodes.push(node)
        processedStates.add(history.fromLevel1 || '')
        processedStates.add(history.toLevel1 || '')
      }
    })

    // 添加当前状态里程碑节点
    const currentNode: FlowNode = {
      id: 'current',
      type: 'milestone',
      title: '当前状态',
      description: `项目当前处于${currentStatus}状态`,
      status: 'active',
      position: { x: generatedNodes.length * 100, y: 50 },
      connections: []
    }
    generatedNodes.push(currentNode)

    setNodes(generatedNodes)
  }

  const getNodeIcon = (node: FlowNode) => {
    switch (node.type) {
      case 'state':
        const config = stateFlowConfig[node.title as keyof typeof stateFlowConfig]
        const Icon = config?.icon || GitCommit
        return <Icon className="h-5 w-5" />
      case 'transition':
        return <GitMerge className="h-5 w-5" />
      case 'milestone':
        return <CheckCircle className="h-5 w-5" />
      default:
        return <GitCommit className="h-5 w-5" />
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active': return 'border-blue-500 bg-blue-50'
      case 'completed': return 'border-green-500 bg-green-50'
      case 'error': return 'border-red-500 bg-red-50'
      default: return 'border-gray-300 bg-gray-50'
    }
  }

  const getStatusBadgeColor = (status: string) => {
    switch (status) {
      case 'active': return 'bg-blue-500'
      case 'completed': return 'bg-green-500'
      case 'error': return 'bg-red-500'
      default: return 'bg-gray-400'
    }
  }

  const formatTime = (timestamp: string) => {
    return new Date(timestamp).toLocaleString('zh-CN')
  }

  return (
    <div className="space-y-6">
      {/* 视图切换 */}
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold">项目状态流转时间线</h3>
        <div className="flex space-x-2">
          <Button
            variant={viewMode === 'timeline' ? 'default' : 'outline'}
            size="sm"
            onClick={() => setViewMode('timeline')}
          >
            时间线视图
          </Button>
          <Button
            variant={viewMode === 'graph' ? 'default' : 'outline'}
            size="sm"
            onClick={() => setViewMode('graph')}
          >
            图谱视图
          </Button>
        </div>
      </div>

      {/* 时间线视图 */}
      <div className="space-y-4">
        {nodes
          .filter(node => node.type === 'transition')
          .sort((a, b) => new Date(a.timestamp || '').getTime() - new Date(b.timestamp || '').getTime())
          .map((node, index) => (
            <div key={node.id} className="flex items-start space-x-4">
              {/* 时间线连接线 */}
              <div className="flex flex-col items-center">
                <div className={cn(
                  "w-4 h-4 rounded-full border-2",
                  getStatusBadgeColor(node.status)
                )} />
                {index < nodes.filter(n => n.type === 'transition').length - 1 && (
                  <div className="w-0.5 h-16 bg-gray-300 mt-2" />
                )}
              </div>

              {/* 节点内容 */}
              <Card className="flex-1">
                <CardHeader className="pb-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      {getNodeIcon(node)}
                      <CardTitle className="text-base">{node.title}</CardTitle>
                      <Badge className={getStatusBadgeColor(node.status)}>
                        {node.status === 'completed' ? '已完成' : '进行中'}
                      </Badge>
                    </div>
                    <div className="text-sm text-gray-500">
                      {formatTime(node.timestamp || '')}
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="pt-0">
                  {node.description && (
                    <p className="text-sm text-gray-600 mb-3">{node.description}</p>
                  )}
                  
                  {node.metadata?.fromStatus && node.metadata?.toStatus && (
                    <div className="flex items-center space-x-2 text-sm">
                      <Badge variant="outline" className="text-xs">
                        {node.metadata.fromStatus}
                      </Badge>
                      <ArrowRight className="h-3 w-3 text-gray-400" />
                      <Badge variant="outline" className="text-xs">
                        {node.metadata.toStatus}
                      </Badge>
                    </div>
                  )}
                  
                  {node.operator && (
                    <div className="flex items-center space-x-2 mt-2 text-xs text-gray-500">
                      <User className="h-3 w-3" />
                      <span>操作人: {node.operator}</span>
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          ))}
      </div>

      {/* 当前状态卡片 */}
      <Card className="border-blue-500 bg-blue-50">
        <CardHeader>
          <CardTitle className="flex items-center space-x-2 text-blue-900">
            <CheckCircle className="h-5 w-5" />
            <span>当前项目状态</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <div className="text-2xl font-bold text-blue-900 mb-2">{currentStatus}</div>
              <p className="text-blue-700">项目当前处于此状态，可以执行相应的流转操作</p>
            </div>
            <Badge className="bg-blue-500 text-white px-4 py-2">
              当前状态
            </Badge>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}